package com.jxb.proxy;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import com.jxb.service.UserService;

/**
 * 类注释
 *
 * @author jiaobo
 * @date Created in 2024/11/24 15:33
 **/
public class CglibTest {

    public static void main(String[] args) {
        UserService target = new UserService();

        //通过cglib技术生成代理类
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(UserService.class);

        //定义代理逻辑
        enhancer.setCallbacks(new Callback[]{new MethodInterceptor() {
            //o代表了代理类
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy)
                    throws Throwable {
                System.out.println("before...");
                //target代表被代理类，执行被代理类的方法
                // Object result = methodProxy.invoke(target, objects);
                //o是代理类，所以这里执行的是代理类父类的方法，也就是被代理类的方法
                // Object result = methodProxy.invokeSuper(o,args);
                //o是代理类，执行代理类的方法
                Object result = method.invoke(o, args);
                System.out.println("after...");
                return result;
            }
        }});
        UserService userService = (UserService) enhancer.create();
        userService.test();
    }

}
